package com.example.pdfsearch.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.pdfsearch.R;
import com.example.pdfsearch.adapter.PDFAdapter;
import com.example.pdfsearch.bean.PDFFileInfo;
import com.example.pdfsearch.util.PDFUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Objects;

import io.reactivex.functions.Consumer;

/**
 * @作者: njb
 * @时间: 2019/9/11 20:31
 * @描述: pdf文件查找
 */
public class PDFSearchActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private ProgressDialog progressDialog;
    private PDFAdapter pdfAdapter;
    private ImageView imgBack;
    private TextView tvTitle;
    private TextView tvFinish;
    private ArrayList<PDFFileInfo> pdfData = new ArrayList<>();
    private String TAG = PDFSearchActivity.class.getSimpleName();
    //private String fileName="TBS测试.docx";
    //private String fileUrl = "http://pic.oss.xadazhihui.cn/statement/12/2019091116105497151.pdf";


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                initRecyclerView();
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_select);
        requestPermission();
        initViews();
        initListener();
    }

    private void requestPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_SETTINGS)
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) {
                            if (permission.granted) {
                                // 用户已经同意该权限

                                Log.d(TAG, permission.name + " is granted.");
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                Log.d(TAG, permission.name + " is denied. More info should be provided.");
                            } else {
                                // 用户拒绝了该权限，并且选中『不再询问』
                                Log.d(TAG, permission.name + " is denied.");
                            }

                        }
                    });
        }
    }

    private void searchFile() {

        new Thread() {
            @Override
            public void run() {
                super.run();
                getFolderData();
            }
        }.start();
    }

    private void initViews() {
        mRecyclerView = findViewById(R.id.rv_pdf);
        imgBack = findViewById(R.id.iv_back);
        tvTitle = findViewById(R.id.tv_title);
        tvFinish = findViewById(R.id.tv_right);
        tvTitle.setText("PDF文件搜索");

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        showDialog();
        searchFile();

    }

    private void initListener() {

    }

    private void showDialog() {
        progressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        progressDialog.setMessage("正在加载数据中...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    @SuppressLint("NewApi")
    private void initRecyclerView() {
        pdfAdapter = new PDFAdapter(null);
        View notDataView = getLayoutInflater().inflate(R.layout.pdf_empty_view, (ViewGroup) mRecyclerView.getParent(), false);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(pdfAdapter);

        pdfAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (!pdfData.get(position).isSelect()) {
                    if (getSelectNumber() >= 3) {
                        Toast.makeText(PDFSearchActivity.this, "最多可选择3个文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                for (int i = 0; i < pdfData.size(); i++) {
                    if (i == position) {
                        if (pdfData.get(i).isSelect()) {
                            pdfData.get(i).setSelect(false);
                        } else {
                            pdfData.get(i).setSelect(true);
                        }
                    }
                }
                adapter.notifyDataSetChanged();

                tvFinish.setText("完成(" + getSelectNumber() + ")");


            }
        });
        if (pdfData != null && pdfData.size() > 0) {

            for (int i = 0; i < pdfData.size(); i++) {
                pdfData.get(i).setSelect(false);
            }
            pdfAdapter.setNewData(pdfData);
        } else {
            pdfAdapter.setEmptyView(notDataView);
        }
        progressDialog.dismiss();
        //跳转到文件预览
        pdfAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String fileUrl = Objects.requireNonNull(pdfAdapter.getItem(position)).getFilePath();
                String fileName = Objects.requireNonNull(pdfAdapter.getItem(position)).getFileName();
                PDFPreViewActivity.actionStart(PDFSearchActivity.this, fileUrl, fileName);
            }
        });
    }


    /**
     * 遍历文件夹中资源
     */
    public void getFolderData() {
        getDocumentData();
        handler.sendEmptyMessage(1);
    }

    /**
     * 获取手机文档数据
     *
     * @param
     */
    public void getDocumentData() {

        String[] columns = new String[]{MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.MIME_TYPE, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.DATA};

        String select = "(_data LIKE '%.pdf')";

        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Files.getContentUri("external"), columns, select, null, null);

        int columnIndexOrThrow_DATA = 0;
        if (cursor != null) {
            columnIndexOrThrow_DATA = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
        }

        if (cursor != null) {
            while (cursor.moveToNext()) {

                String path = cursor.getString(columnIndexOrThrow_DATA);

                PDFFileInfo document = PDFUtil.getFileInfoFromFile(new File(path));

                pdfData.add(document);
                Log.d(TAG, " pdf " + document);
            }
        }
        cursor.close();
    }

    private int getSelectNumber() {
        int k = 0;
        for (int i = 0; i < pdfData.size(); i++) {
            if (pdfData.get(i).isSelect()) {
                k++;
            }
        }
        return k;
    }

}
